<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 7.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha256-wiz7ZSCn/btzhjKDQBms9Hx4sSeUYsDrTLg7roPstac=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.css" integrity="sha256-6cQIC71/iBIYXFK+0RHAvwmjwWzkWd+r7v/BX3/vZDc=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/themes/green/pace-theme-minimal.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/pace.min.js" integrity="sha256-gqd7YTjg/BtfqWSwsJOvndl0Bxc8gFImLEkXQT8+qj0=" crossorigin="anonymous"></script>

<script class="next-config" data-name="main" type="application/json">{"hostname":"sumumm.github.io","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.19.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":true,"height":300},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="本文主要是STM32开发——SysTick定时器的一些相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:type" content="article">
<meta property="og:title" content="LV16-17-SysTick定时器">
<meta property="og:url" content="https://sumumm.github.io/post/787934fe.html">
<meta property="og:site_name" content="苏木">
<meta property="og:description" content="本文主要是STM32开发——SysTick定时器的一些相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230504174101760.png">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230502220435769.png">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230502221111875.png">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230502221243224.png">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230502221441225.png">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230502221638199.png">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230502222837622.png">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230502223053352.png">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230503105812871.png">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230503112220723.png">
<meta property="article:published_time" content="2023-06-04T14:07:04.000Z">
<meta property="article:modified_time" content="2025-06-13T16:25:57.010Z">
<meta property="article:author" content="苏木">
<meta property="article:tag" content="LV16-STM32开发">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230504174101760.png">


<link rel="canonical" href="https://sumumm.github.io/post/787934fe.html">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://sumumm.github.io/post/787934fe.html","path":"post/787934fe.html","title":"LV16-17-SysTick定时器"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>LV16-17-SysTick定时器 | 苏木</title>
  








    <script src="/js/browser_tools_disable.js"></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<!-- hexo injector head_end start --><link rel="stylesheet" href="https://unpkg.com/hexo-next-tags-plus@latest/lib/tag_plus.css" media="defer" onload="this.media='all'"><!-- hexo injector head_end end --></head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">苏木</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">我的学习之路</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>苏木的家</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类页<span class="badge">42</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档页<span class="badge">673</span></a></li><li class="menu-item menu-item-flink"><a href="/flink/" rel="section"><i class="fa fa-link fa-fw"></i>友人帐</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于我</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%80%E3%80%81SysTick%E5%AE%9A%E6%97%B6%E5%99%A8%E7%AE%80%E4%BB%8B"><span class="nav-text">一、SysTick定时器简介</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E5%9F%BA%E6%9C%AC%E5%8E%9F%E7%90%86"><span class="nav-text">二、基本原理</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E5%8E%9F%E7%90%86%E4%BB%8B%E7%BB%8D"><span class="nav-text">1. 原理介绍</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%AE%9A%E6%97%B6%E6%97%B6%E9%95%BF"><span class="nav-text">2. 定时时长</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%89%E3%80%81%E7%9B%B8%E5%85%B3%E5%AF%84%E5%AD%98%E5%99%A8"><span class="nav-text">三、相关寄存器</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E6%8E%A7%E5%88%B6%E5%92%8C%E7%8A%B6%E6%80%81%E5%AF%84%E5%AD%98%E5%99%A8%EF%BC%88-STK-CTRL%EF%BC%89"><span class="nav-text">1. 控制和状态寄存器（ STK_CTRL）  </span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%8A%A0%E8%BD%BD%E5%80%BC%E5%AF%84%E5%AD%98%E5%99%A8%EF%BC%88-STK-LOAD%EF%BC%89"><span class="nav-text">2. 加载值寄存器（ STK_LOAD）  </span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E5%BD%93%E5%89%8D%E5%80%BC%E5%AF%84%E5%AD%98%E5%99%A8%EF%BC%88-STK-VAL%EF%BC%89"><span class="nav-text">3. 当前值寄存器（ STK_VAL）  </span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E6%A0%A1%E5%87%86%E5%80%BC%E5%AF%84%E5%AD%98%E5%99%A8%EF%BC%88-STK-CALIB%EF%BC%89"><span class="nav-text">4. 校准值寄存器（ STK_CALIB）  </span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%9B%9B%E3%80%81%E6%97%B6%E9%92%9F%E6%9D%A5%E6%BA%90"><span class="nav-text">四、时钟来源</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%94%E3%80%81%E4%B8%AD%E6%96%AD%E4%BC%98%E5%85%88%E7%BA%A7%EF%BC%9F"><span class="nav-text">五、中断优先级？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%85%AD%E3%80%81%E7%9B%B8%E5%85%B3HAL%E5%BA%93%E5%87%BD%E6%95%B0"><span class="nav-text">六、相关HAL库函数</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-HAL-Init-%E4%B8%AD%E7%9A%84%E9%85%8D%E7%BD%AE"><span class="nav-text">1. HAL_Init()中的配置</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-HAL-Init"><span class="nav-text">1.1 HAL_Init()  </span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-HAL-InitTick"><span class="nav-text">1.2 HAL_InitTick()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-HAL-SYSTICK-Config"><span class="nav-text">1.3 HAL_SYSTICK_Config()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-4-SysTick-Config"><span class="nav-text">1.4 SysTick_Config</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-5-%E9%97%AE%E9%A2%98%EF%BC%9F"><span class="nav-text">1.5 问题？</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-SystemClock-Config-%E4%B8%AD%E7%9A%84%E9%85%8D%E7%BD%AE"><span class="nav-text">2. SystemClock_Config()中的配置</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-SystemClock-Config"><span class="nav-text">2.1 SystemClock_Config()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-HAL-RCC-ClockConfig"><span class="nav-text">2.2 HAL_RCC_ClockConfig()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-HAL-InitTick"><span class="nav-text">2.3 HAL_InitTick()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-4-HAL-SYSTICK-Config"><span class="nav-text">2.4 HAL_SYSTICK_Config()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-5-SysTick-Config"><span class="nav-text">2.5 SysTick_Config()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-6-%E4%B8%AD%E6%96%AD%E4%BA%A7%E7%94%9F%E6%97%B6%E9%97%B4"><span class="nav-text">2.6 中断产生时间</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E4%B8%AD%E6%96%AD%E5%A4%84%E7%90%86%E5%87%BD%E6%95%B0"><span class="nav-text">3. 中断处理函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-HAL-Delay"><span class="nav-text">4. HAL_Delay()</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="苏木"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">苏木</p>
  <div class="site-description" itemprop="description">莫道桑榆晚，为霞尚满天</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">673</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">42</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">43</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/sumumm" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;sumumm" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://sumumm.github.io/post/787934fe.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="苏木">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="苏木">
      <meta itemprop="description" content="莫道桑榆晚，为霞尚满天">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="LV16-17-SysTick定时器 | 苏木">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          LV16-17-SysTick定时器
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-06-04 22:07:04" itemprop="dateCreated datePublished" datetime="2023-06-04T22:07:04+08:00">2023-06-04</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">嵌入式开发</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/" itemprop="url" rel="index"><span itemprop="name">01HQ课程体系</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">LV16-STM32开发</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>6.3k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>23 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>本文主要是STM32开发——SysTick定时器的一些相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。</p>
<span id="more"></span>

<!-- Photo: https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/ -->

<details class="folding-tag" blue><summary> 点击查看使用工具及版本 </summary>
              <div class='content'>
              <table>    <tr>        <td align="center" width=150px>Windows</td>        <td align="left">windows11</td>    </tr>    <tr>        <td align="center">Ubuntu</td>        <td align="left">Ubuntu16.04的64位版本</td>      </tr>    <tr>        <td align="center">VMware® Workstation 16 Pro</td>        <td align="left">16.2.3 build-19376536</td>      </tr>    <tr>        <td align="center">SecureCRT</td>        <td align="left">Version 8.7.2 (x64 build 2214)   -   正式版-2020年5月14日</td>      </tr>    <tr>        <td align="center">开发板</td>        <td align="left">正点原子 i.MX6ULL Linux阿尔法开发板</td>      </tr>    <tr>        <td align="center">uboot</td>        <td align="left">NXP官方提供的uboot，NXP提供的版本为uboot-imx-rel_imx_4.1.15_2.1.0_ga(使用的uboot版本为U-Boot 2016.03)</td>      </tr>    <tr>        <td align="center">linux内核</td>        <td align="left">linux-4.15(NXP官方提供)</td>      </tr>    <tr>        <td align="center">STM32开发板</td>        <td align="left">正点原子战舰V3(STM32F103ZET6)</td>      </tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看本文参考资料 </summary>
              <div class='content'>
              <ul><li>通用</li></ul><table><tr><td align="center">分类  </td><td align="center">网址</td><td align="center">说明</td></tr><tr><td align="center" rowspan="4">官方网站</td><td align="left"><a href="https://www.arm.com/" target="_blank">https://www.arm.com/</a></td><td align="left">ARM官方网站，在这里我们可以找到Cotex-Mx以及ARMVx的一些文档</td></tr><tr>                                            <td align="left"><a href="https://www.st.com/content/st_com/zh.html" target="_blank">https://www.st.com/content/st_com/zh.html</a></td><td align="left">ST官方网站，在这里我们可以找到STM32的相关文档</td></tr><tr>                                            <td align="left"><a href="https://www.stmcu.com.cn/" target="_blank">https://www.stmcu.com.cn/</a></td><td align="left">意法半导体ST中文官方网站，在这里我们可以找到STM32的相关中文参考文档</td></tr><tr>                                            <td align="left"><a href="http://elm-chan.org/fsw/ff/00index_e.html" target="_blank">http://elm-chan.org/fsw/ff/00index_e.html</a></td><td align="left">FatFs文件系统官网</td></tr><tr><td align="center" rowspan="3">教程书籍</td><td align="left"><a href="STM32开发相关资料/01ARM参考资料/ARM Cortex-M3权威指南(中文).pdf" target="_blank">《ARM Cortex-M3权威指南》</a></td><td alirn="left" rowspan="3">ARM公司专家Joseph Yiu（姚文祥）的力作，中文翻译是NXP的宋岩</td></tr><tr>                                            <td align="left"><a href="STM32开发相关资料/01ARM参考资料/ARM Cortex-M0权威指南(中文).pdf" target="_blank">《ARM Cortex-M0权威指南》</a></td></tr><tr>                                            <td align="left"><a href="" target="_blank">《ARM Cortex-M3与Cortex-M4权威指南》</a></td></tr><tr><td align="center" rowspan="4">开发论坛</td><td align="left"><a href="http://47.111.11.73/forum.php" target="_blank">http://47.111.11.73/forum.php</a></td><td align="left">开源电子网，正点原子的资料下载及问题讨论论坛</td></tr><tr>                                            <td align="left"><a href="https://www.firebbs.cn/forum.php" target="_blank">https://www.firebbs.cn/forum.php</a></td><td align="left">国内Kinetis开发板-野火/秉火（刘火良）主持的论坛，现也做STM32和i.MX RT</td></tr><tr>                                            <td align="left"><a href="https://www.amobbs.com/index.php" target="_blank">https://www.amobbs.com/index.php</a></td><td align="left">阿莫（莫进明）主持的论坛，号称国内最早最火的电子论坛，以交流Atmel AVR系列单片机起家，现已拓展到嵌入式全平台，其STM32系列帖子有70W+。</td></tr><tr>                                            <td align="left"><a href="http://download.100ask.net/index.html" target="_blank">http://download.100ask.net/index.html</a></td><td align="left">韦东山嵌入式资料中心，有些STM32和linux的相关资料也可以来这里找。</td></tr><tr><td align="center" rowspan="3">博客参考</td><td align="left"><a href="http://www.openedv.com/" target="_blank">http://www.openedv.com/</a></td><td align="left">开源网-原子哥个人博客</td></tr><tr>                                            <td align="left"><a href="http://blog.chinaaet.com/jihceng0622" target="_blank">http://blog.chinaaet.com/jihceng0622</a></td><td align="left">博主是原Freescale现NXP的现场应用工程师</td></tr><tr>                                            <td align="left"><a href="https://community.arm.com/arm-community-blogs/b/architectures-and-processors-blog/posts/cortex-m-resources" target="_blank">cortex-m-resources</a></td><td align="left">这其实并不算是一个博客，这是ARM公司专家Joseph Yiu收集整理的所有对开发者有用的官方Cortex-M资料链接（也包含极少数外部资源链接）</td></tr></table><ul><li>STM32</li></ul><table>    <tr><td align="center" rowspan="2">STM32</td><td align="left"><a href="https://doc.embedfire.com/mcu/stm32/f103/hal_general/zh/latest/index.html" target="_blank">STM32 HAL库开发实战指南——基于F103系列开发板</a></td><td align="left">野火STM32开发教程在线文档</td></tr><tr>                                            <td align="left"><a href="https://doc.embedfire.com/mcu/stm32/f103badao/std/zh/latest/index.html" target="_blank">STM32库开发实战指南——基于野火霸道开发板</a></td><td align="left">野火STM32开发教程在线文档</td></tr></table><ul><li>SD卡</li></ul><table>    <tr><td align="left"><a href="https://www.sdcard.org/" target="_blank">SD Association</a></td><td align="left">提供了SD存储卡和SDIO卡系统规范</td></tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看相关文件下载 </summary>
              <div class='content'>
              <table>    <tr><td align="left"><a href="https://www.st.com/resource/en/datasheet/stm32f103ze.pdf" target="_blank">STM32F103xx英文数据手册</a></td><td align="left">STM32F103xC/D/E系列的英文数据手册</td></tr>    <tr><td align="left"><a href="https://www.stmcu.com.cn/Designresource/detail/localization_document%20/709978" target="_blank">STM32F103xx中文数据手册</a></td><td align="left">STM32F103xC/D/E系列的中文数据手册</td></tr>    <tr><td align="left"><a href="https://www.st.com/resource/en/reference_manual/rm0008-stm32f101xx-stm32f102xx-stm32f103xx-stm32f105xx-and-stm32f107xx-advanced-armbased-32bit-mcus-stmicroelectronics.pdf" target="_blank">STM32F10xxx英文参考手册（RM0008）</a></td><td align="left">STM32F10xxx系列的英文参考手册</td></tr>    <tr><td align="left"><a href="https://www.stmcu.com.cn/Designresource/detail/localization_document%20/710001" target="_blank">STM32F10xxx中文参考手册（RM0008）</a></td><td align="left">STM32F10xxx系列的中文参考手册</td></tr>    <tr><td align="left"><a href="https://developer.arm.com/documentation/100165/0201/?lang=en" target="_blank">Arm Cortex-M3 处理器技术参考手册-英文版</a></td><td align="left">Cortex-M3技术参考手册-英文版</td></tr>    <tr><td align="left"><a href="https://www.st.com/resource/en/programming_manual/pm0056-stm32f10xxx20xxx21xxxl1xxxx-cortexm3-programming-manual-stmicroelectronics.pdf" target="_blank">STM32F10xxx Cortex-M3编程手册-英文版(PM0056)</a></td><td align="left">STM32F10xxx/20xxx/21xxx/L1xxxx系列Cortex-M3编程手册-英文版</td></tr>    <tr><td align="left"><a href="https://www.sdcard.org/downloads/pls/" target="_blank">SD卡相关资料——最新版本</a></td><td align="left">有关SD卡的一些资料可以从这里下载</td></tr>    <tr><td align="left"><a href="https://www.sdcard.org/downloads/pls/archives/" target="_blank">SD卡相关资料——历史版本</a></td><td align="left">有关SD卡的一些历史版本资料可以从这里下载，比如后边看的SD卡2.0协议</td></tr>    <tr><td align="left"><a href="./" target="_blank">SD 2.0 协议标准完整版</a></td><td align="left">这是一篇关于SD卡2.0协议的中文文档，还是比较有参考价值的，可以一看</td></tr></table>
              </div>
            </details>

<p>这一部分我们可以查看[《ARM Cortex-M3权威指南(中文).pdf》](STM32开发相关资料&#x2F;01ARM参考资料&#x2F;ARM Cortex-M3权威指南(中文).pdf)的 第8章NVIC与中断控制 中的 SysTick定时器  小节。</p>
<h1 id="一、SysTick定时器简介"><a href="#一、SysTick定时器简介" class="headerlink" title="一、SysTick定时器简介"></a><font size=3>一、SysTick定时器简介</font></h1><p>SysTick定时器(又名系统滴答定时器)是存在于Cortex-M3的一个定时器，只要是ARM Cotex-M系列内核的MCU都包含这个定时器。使用内核的SysTick定时器来实现延时，可以不占用系统定时器，节约资源。由于SysTick是在CPU核内部实现的，跟MCU外设无关， 因此它的代码可以在不同厂家之间移植。  </p>
<p>SysTick定时器被捆绑在NVIC中，用于产生SYSTICK异常（异常号： 15）。在以前，大多操作系统需要一个硬件定时器来产生操作系统需要的滴答中断，作为整个系统的时基。例如，为多个任务许以不同数目的时间片，确保没有一个任务能霸占系统；或者把每个定时器周期的某个时间范围赐予特定的任务等，还有操作系统提供的各种定时功能，都与这个滴答定时器有关，有了它，就可以根据这个中断，系统就可以实现时间片的计算从而切换进程。因此，需要一个定时器来产生周期性的中断，而且最好还让用户程序不能随意访问它的寄存器，以维持操作系统“心跳”的节律。</p>
<p>Cortex‐M3处理器内部包含了一个简单的定时器。因为所有的CM3芯片都带有这个定时器，软件在不同 CM3器件间的移植工作得以化简。该定时器的时钟源可以是内部时钟（FCLK，CM3上的自由运行时钟），或者是外部时钟（ CM3处理器上的STCLK信号）。不过， STCLK的具体来源则由芯片设计者决定，因此不同产品之间的时钟频率可能会大不相同，需要检视芯片的器件手册来决定选择什么作为时钟源。</p>
<p>SysTick定时器能产生中断， CM3为它专门开出一个异常类型，并且在向量表中有它的一席之地。它使操作系统和其它系统软件在CM3器件间的移植变得简单多了，因为在所有CM3产品间对其处理都是相同的。  </p>
<h1 id="二、基本原理"><a href="#二、基本原理" class="headerlink" title="二、基本原理"></a><font size=3>二、基本原理</font></h1><h2 id="1-原理介绍"><a href="#1-原理介绍" class="headerlink" title="1. 原理介绍"></a><font size=3>1. 原理介绍</font></h2><p>SysTick定时器是一个24位递减定时器，即计数器可以从最大值2^24开始， 每个时钟周期减1，当减到0时，会产生Systick异常，同时再自动重载定时初值，开始新一轮计数。如下图递减计数器在时钟的驱动下，从重装载寄存器初值开始往下递减计数到0，产生中断和置位COUNTFLAG标志。然后又从重装载寄存器初值值开始重新递减计数，如此循环。  </p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230504174101760.png" alt="image-20230504174101760" style="zoom: 33%;" />



<p> 通过设置这个重装载寄存器初值，就可以实现得到指定时间。如下图所示：</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230502220435769.png" alt="image-20230502220435769" style="zoom: 67%;" />

<p> y为定时器初值，然后随着时间增加， 值逐渐减小，直至为0，再重新加载初值，如此往复，0<del>t1、 t1</del>t2、 t2~t3这些时间段，就是我们需要的延时时间。  </p>
<p>假设STM32F103工作在72MHz，即72000000Hz，意味着1s时间内，会计数72000000次。那么1ms则计数72000000&#x2F;1000&#x3D;72000次。这个72000就可以作为系统滴答定时器的初始值，将这个值写入系统滴答定时器，定时器在每个时钟周期减1，减到0时，就刚好是1ms，同时产生中断通知，再次加载72000到系统滴答定时器。如此反复。 HAL库提供“ HAL_SYSTICK_Config()”函数去设置这个初始值 。</p>
<h2 id="2-定时时长"><a href="#2-定时时长" class="headerlink" title="2. 定时时长"></a><font size=3>2. 定时时长</font></h2><p>（1）t：一个计数循环的时间，跟reload和CLK有关</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">reload * (<span class="number">1</span> / clk)</span><br></pre></td></tr></table></figure>

<p>（2）CLK： 72M或者9M，由CTRL寄存器配置</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Clk = <span class="number">72</span>M时， reload=<span class="number">72</span>：t = (<span class="number">72</span>) *(<span class="number">1</span>/<span class="number">72</span>M) = <span class="number">1U</span>S      </span><br><span class="line">Clk = <span class="number">72</span>M时， reload=<span class="number">72000</span>：t = (<span class="number">72000</span>) *(<span class="number">1</span>/ <span class="number">72</span> M )= <span class="number">1</span>MS</span><br></pre></td></tr></table></figure>

<p>（3）RELOAD： 24位，用户自己配置  </p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">0</span>~<span class="number">0xFFFFFF</span></span><br></pre></td></tr></table></figure>

<p>（4）时间换算</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>s = <span class="number">1000</span>ms = <span class="number">1000</span> <span class="number">000</span> us = <span class="number">1000</span> <span class="number">000</span> <span class="number">000</span>ns</span><br></pre></td></tr></table></figure>



<h1 id="三、相关寄存器"><a href="#三、相关寄存器" class="headerlink" title="三、相关寄存器"></a><font size=3>三、相关寄存器</font></h1><p>对于STM32的系统滴答定时器相关的寄存器我们可以查看 <a target="_blank" rel="noopener" href="https://www.st.com/resource/en/programming_manual/pm0056-stm32f10xxx20xxx21xxxl1xxxx-cortexm3-programming-manual-stmicroelectronics.pdf">STM32F10xxx_Cortex-M3编程手册</a> 的4.5 SysTick timer (STK)这一节。</p>
<h2 id="1-控制和状态寄存器（-STK-CTRL）"><a href="#1-控制和状态寄存器（-STK-CTRL）" class="headerlink" title="1. 控制和状态寄存器（ STK_CTRL）  "></a><font size=3>1. 控制和状态寄存器（ STK_CTRL）  </font></h2><img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230502221111875.png" alt="image-20230502221111875" style="zoom:50%;" />

<p>相关位说明如下：</p>
<table>
<thead>
<tr>
<th>位段</th>
<th>名称</th>
<th align="center">类型</th>
<th align="center">复位值</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>[31:17 ]</td>
<td>RESERVED</td>
<td align="center">R</td>
<td align="center">0</td>
<td>保留位</td>
</tr>
<tr>
<td>[16]</td>
<td>COUNTFLAG</td>
<td align="center">RW</td>
<td align="center">0</td>
<td>如果在上次读取本寄存器后，计数器已经计到 了 0，则该位为 1；读取该位，该位将自动清零</td>
</tr>
<tr>
<td>[15:3]</td>
<td>RESERVED</td>
<td align="center">R</td>
<td align="center">0</td>
<td>保留</td>
</tr>
<tr>
<td>[2]</td>
<td>CLKSOURCE</td>
<td align="center">RW</td>
<td align="center">0</td>
<td>0&#x3D;AHB&#x2F;8；1&#x3D;AHB</td>
</tr>
<tr>
<td>[1]</td>
<td>TICKINT</td>
<td align="center">RW</td>
<td align="center">0</td>
<td>1&#x3D;计数器计数到 0 时产生 SysTick 异常请求 0&#x3D;计数器计数到 0 时不产生异常</td>
</tr>
<tr>
<td>[0]</td>
<td>ENABLE</td>
<td align="center">RW</td>
<td align="center">0</td>
<td>SysTick 定时器的使能位</td>
</tr>
</tbody></table>
<p>重点关注Bit[0]，用于使能系统滴答定时器， Bit[1]使能系统滴答定时器中断， Bit[2]系统滴答时钟的时钟来源。  </p>
<h2 id="2-加载值寄存器（-STK-LOAD）"><a href="#2-加载值寄存器（-STK-LOAD）" class="headerlink" title="2. 加载值寄存器（ STK_LOAD）  "></a><font size=3>2. 加载值寄存器（ STK_LOAD）  </font></h2><img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230502221243224.png" alt="image-20230502221243224" style="zoom:50%;" />

<table>
<thead>
<tr>
<th>位段</th>
<th>名称</th>
<th align="center">类型</th>
<th align="center">复位值</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>[31:24]</td>
<td>RESERVED</td>
<td align="center">R</td>
<td align="center">0</td>
<td>保留位</td>
</tr>
<tr>
<td>[23:0]</td>
<td>RELOAD</td>
<td align="center">RW</td>
<td align="center">0</td>
<td>当计数器向下计数到 0 时,下一个时钟滴答定 时器将重新装载的值</td>
</tr>
</tbody></table>
<p>Bit[23:0]，一共24位，用来设置系统滴答定时器的初始值，因此范围为1~ 16777216。 </p>
<h2 id="3-当前值寄存器（-STK-VAL）"><a href="#3-当前值寄存器（-STK-VAL）" class="headerlink" title="3. 当前值寄存器（ STK_VAL）  "></a><font size=3>3. 当前值寄存器（ STK_VAL）  </font></h2><img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230502221441225.png" alt="image-20230502221441225" style="zoom:50%;" />

<table>
<thead>
<tr>
<th>位段</th>
<th>名称</th>
<th align="center">类型</th>
<th align="center">复位值</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>[31:24]</td>
<td>RESERVED</td>
<td align="center">R</td>
<td align="center">0</td>
<td>保留位</td>
</tr>
<tr>
<td>[23:0]</td>
<td>RELOAD</td>
<td align="center">RW</td>
<td align="center">0</td>
<td>读取时返回当前计数的值，写它则使之清零，<br> 同时还会清除在 SysTick 控制及状态寄存器 中的 COUNTFLAG 标志</td>
</tr>
</tbody></table>
<p>Bit[23:0]，一共24位，用来获取当前系统滴答定时器的计数值。  </p>
<h2 id="4-校准值寄存器（-STK-CALIB）"><a href="#4-校准值寄存器（-STK-CALIB）" class="headerlink" title="4. 校准值寄存器（ STK_CALIB）  "></a><font size=3>4. 校准值寄存器（ STK_CALIB）  </font></h2><img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230502221638199.png" alt="image-20230502221638199" style="zoom:50%;" />

<table>
<thead>
<tr>
<th>位段</th>
<th>名称</th>
<th align="center">类型</th>
<th align="center">复位值</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>[31]</td>
<td>NOREF</td>
<td align="center">R</td>
<td align="center">-</td>
<td>1&#x3D;没有外部参考时钟（ STCLK 不可用； 0&#x3D;外部参考时钟可用</td>
</tr>
<tr>
<td>[30]</td>
<td>SKEW</td>
<td align="center">R</td>
<td align="center">-</td>
<td>1&#x3D;校准值不是准确的 10ms；0&#x3D;校准值是准确的 10ms</td>
</tr>
<tr>
<td>[29:24]</td>
<td>RESERVED</td>
<td align="center">R</td>
<td align="center">0</td>
<td>保留</td>
</tr>
<tr>
<td>[23:0]</td>
<td>TENMS</td>
<td align="center">RW</td>
<td align="center">0</td>
<td>10ms 校准值。芯片设计者应该通过 Cortex-M3 的输入信号提供该数值。若该值读回零，则表 示无法使用校准功能</td>
</tr>
</tbody></table>
<p>这个寄存器没用到，可以不用管。 此外，当处理器在调试期间被暂停（ halt ）时， 系统滴答定时器也将暂停运作。  </p>
<h1 id="四、时钟来源"><a href="#四、时钟来源" class="headerlink" title="四、时钟来源"></a><font size=3>四、时钟来源</font></h1><p>我们了解了寄存器之后其实就可以编程了，但是还有一个问题，那就是，它的时钟哪来的？我们看一下STM32的时钟树的这一部分：</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230502222837622.png" alt="image-20230502222837622" style="zoom:50%;" />

<p>我们可以看左侧图红线这一条路，AHB时钟讲过1或者8分频后送至Cortex系统时钟，系统滴答定时器使用的就是这个时钟，在这个时钟的驱动下，Cortex-M3内核中的系统滴答定时器寄存器值就开始递减：</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230502223053352.png" alt="image-20230502223053352" style="zoom:50%;" />

<h1 id="五、中断优先级？"><a href="#五、中断优先级？" class="headerlink" title="五、中断优先级？"></a><font size=3>五、中断优先级？</font></h1><p>SysTick属于内核里面的外设，他的中断优先级跟片上的外设的中断优先级相比，哪个高？  </p>
<p>systick中断优先级配置的是scb-&gt;shprx寄存器；而外设的中断优先级配置的是nvic-&gt;iprx，有优先级分组，有抢占优先级和子优先级的说法。STM32里面无论是内核还是外设都是使用4个二进制位来表示中断优先级。    </p>
<p>中断优先级的分组对内核和外设同样适用。当比较的时候，只需要把内核外设的中断优先级的四个位按照外设的中断优先级来分组来解析即可，即人为的分出抢占优先级和子优先级。  </p>
<h1 id="六、相关HAL库函数"><a href="#六、相关HAL库函数" class="headerlink" title="六、相关HAL库函数"></a><font size=3>六、相关HAL库函数</font></h1><p>HAL库函数对系统滴答定时器的相关操作在这里：</p>
<h2 id="1-HAL-Init-中的配置"><a href="#1-HAL-Init-中的配置" class="headerlink" title="1. HAL_Init()中的配置"></a><font size=3>1. HAL_Init()中的配置</font></h2><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">main()---&gt;HAL_Init()---&gt;HAL_InitTick()---&gt;HAL_SYSTICK_Config()</span><br></pre></td></tr></table></figure>

<h3 id="1-1-HAL-Init"><a href="#1-1-HAL-Init" class="headerlink" title="1.1 HAL_Init()  "></a><font size=3>1.1 HAL_Init()  </font></h3><p>我们先来看一下这个 HAL_Init 函数：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">HAL_StatusTypeDef <span class="title function_">HAL_Init</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="comment">// 中间部分省略...</span></span><br><span class="line">  <span class="comment">/* Set Interrupt Group Priority */</span></span><br><span class="line">  HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);</span><br><span class="line"></span><br><span class="line">  <span class="comment">/* Use systick as time base source and configure 1ms tick (default clock after Reset is HSI) */</span></span><br><span class="line">  HAL_InitTick(TICK_INT_PRIORITY);</span><br><span class="line">  <span class="comment">// 中间部分省略...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>首先是 HAL_NVIC_SetPriorityGrouping函数设置了NVIC中断分组为组4，这个是我们在STM32CubeMX中配置的。</p>
<p>然后调用了 HAL_InitTick() 函数来初始化系统滴答定时器，传入的参数为 TICK_INT_PRIORITY，它起始就是个 0 ：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">define</span>  TICK_INT_PRIORITY            0U    <span class="comment">/*!&lt; tick interrupt priority (lowest by default)  *</span></span></span><br></pre></td></tr></table></figure>

<h3 id="1-2-HAL-InitTick"><a href="#1-2-HAL-InitTick" class="headerlink" title="1.2 HAL_InitTick()"></a><font size=3>1.2 HAL_InitTick()</font></h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">__weak HAL_StatusTypeDef <span class="title function_">HAL_InitTick</span><span class="params">(<span class="type">uint32_t</span> TickPriority)</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="comment">/* Configure the SysTick to have interrupt in 1ms time basis*/</span></span><br><span class="line">  <span class="keyword">if</span> (HAL_SYSTICK_Config(SystemCoreClock / (<span class="number">1000U</span> / uwTickFreq)) &gt; <span class="number">0U</span>)</span><br><span class="line">  &#123;</span><br><span class="line">    <span class="keyword">return</span> HAL_ERROR;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/* Configure the SysTick IRQ priority */</span></span><br><span class="line">  <span class="keyword">if</span> (TickPriority &lt; (<span class="number">1UL</span> &lt;&lt; __NVIC_PRIO_BITS))</span><br><span class="line">  &#123;</span><br><span class="line">    HAL_NVIC_SetPriority(SysTick_IRQn, TickPriority, <span class="number">0U</span>);</span><br><span class="line">    uwTickPrio = TickPriority;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">else</span></span><br><span class="line">  &#123;</span><br><span class="line">    <span class="keyword">return</span> HAL_ERROR;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/* Return function status */</span></span><br><span class="line">  <span class="keyword">return</span> HAL_OK;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>进来之后发现，这是个弱函数哎，我们打开对应的头文件会发现，声明的时候并没有带__weak符号：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">HAL_StatusTypeDef <span class="title function_">HAL_InitTick</span><span class="params">(<span class="type">uint32_t</span> TickPriority)</span>;</span><br></pre></td></tr></table></figure>

<p>这就说明，当我们没有重写这个函数的时候，默认会调用这个弱函数。我们先看下边的 HAL_NVIC_SetPriority这一行，这里就是在设置系统滴答定时器中断的优先级，从 TICK_INT_PRIORITY 宏我们知道这里形参 TickPriority 的值就是 0，具体的就先不看了。我们再来看一下滴答定时器配置时传入的参数：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">HAL_SYSTICK_Config(SystemCoreClock / (<span class="number">1000U</span> / uwTickFreq))</span><br></pre></td></tr></table></figure>

<p>我们追踪一下这里的两个参数：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">uint32_t</span> SystemCoreClock = <span class="number">16000000</span>;<span class="comment">// 定义时的默认值，后边配置时钟的时候这个值会被修改</span></span><br><span class="line"></span><br><span class="line">HAL_TickFreqTypeDef uwTickFreq = HAL_TICK_FREQ_DEFAULT;  <span class="comment">/* 1KHz */</span></span><br></pre></td></tr></table></figure>

<p>这个 HAL_TICK_FREQ_DEFAULT是什么？我们继续追踪：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">enum</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">  HAL_TICK_FREQ_10HZ         = <span class="number">100U</span>,</span><br><span class="line">  HAL_TICK_FREQ_100HZ        = <span class="number">10U</span>,</span><br><span class="line">  HAL_TICK_FREQ_1KHZ         = <span class="number">1U</span>,</span><br><span class="line">  HAL_TICK_FREQ_DEFAULT      = HAL_TICK_FREQ_1KHZ</span><br><span class="line">&#125; HAL_TickFreqTypeDef;</span><br></pre></td></tr></table></figure>

<p>从这里我们知道 HAL_TICK_FREQ_DEFAULT 的值为1，于是，上边传入 HAL_SYSTICK_Config()函数的参数就为：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">SystemCoreClock / (<span class="number">1000U</span> / uwTickFreq) = <span class="number">16000000</span> / (<span class="number">1000</span> / <span class="number">1</span>) = <span class="number">16000</span></span><br><span class="line"><span class="comment">// 即</span></span><br><span class="line"><span class="keyword">if</span> (HAL_SYSTICK_Config(<span class="number">16000</span>) &gt; <span class="number">0U</span>)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">return</span> HAL_ERROR;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="1-3-HAL-SYSTICK-Config"><a href="#1-3-HAL-SYSTICK-Config" class="headerlink" title="1.3 HAL_SYSTICK_Config()"></a><font size=3>1.3 HAL_SYSTICK_Config()</font></h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">uint32_t</span> <span class="title function_">HAL_SYSTICK_Config</span><span class="params">(<span class="type">uint32_t</span> TicksNumb)</span></span><br><span class="line">&#123;</span><br><span class="line">   <span class="keyword">return</span> SysTick_Config(TicksNumb);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这个就简单了，直接返回了另一个函数调用后的值，新调用的函数的形参 TicksNumb 就等于 上边计算出来的 16000。</p>
<h3 id="1-4-SysTick-Config"><a href="#1-4-SysTick-Config" class="headerlink" title="1.4 SysTick_Config"></a><font size=3>1.4 SysTick_Config</font></h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">__STATIC_INLINE <span class="type">uint32_t</span> <span class="title function_">SysTick_Config</span><span class="params">(<span class="type">uint32_t</span> ticks)</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="keyword">if</span> ((ticks - <span class="number">1UL</span>) &gt; SysTick_LOAD_RELOAD_Msk)</span><br><span class="line">  &#123;</span><br><span class="line">    <span class="keyword">return</span> (<span class="number">1UL</span>);                                                   <span class="comment">/* Reload value impossible */</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  SysTick-&gt;LOAD  = (<span class="type">uint32_t</span>)(ticks - <span class="number">1UL</span>);                         <span class="comment">/* set reload register */</span></span><br><span class="line">  NVIC_SetPriority (SysTick_IRQn, (<span class="number">1UL</span> &lt;&lt; __NVIC_PRIO_BITS) - <span class="number">1UL</span>); <span class="comment">/* set Priority for Systick Interrupt */</span></span><br><span class="line">  SysTick-&gt;VAL   = <span class="number">0UL</span>;                                             <span class="comment">/* Load the SysTick Counter Value */</span></span><br><span class="line">  SysTick-&gt;CTRL  = SysTick_CTRL_CLKSOURCE_Msk |</span><br><span class="line">                   SysTick_CTRL_TICKINT_Msk   |</span><br><span class="line">                   SysTick_CTRL_ENABLE_Msk;                         <span class="comment">/* Enable SysTick IRQ and SysTick Timer */</span></span><br><span class="line">  <span class="keyword">return</span> (<span class="number">0UL</span>);                                                     <span class="comment">/* Function successful */</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在这个函数中对系统滴答定时器的寄存器进行配置，可以看到加载值寄存器的值配置为了 ticks -1 ,按前边的16000算的话，这里应该是15999。</p>
<h3 id="1-5-问题？"><a href="#1-5-问题？" class="headerlink" title="1.5 问题？"></a><font size=3>1.5 问题？</font></h3><p>上边就是从HAL_Init()函数到配置寄存器的函数调用及参数调用关系，但是吧，这个时候还没有初始化和配置RCC时钟哎，也不知道在这里进行一遍初始化的目的是什么。注释是这样写的：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Reset of all peripherals, Initializes the Flash interface and the Systick. */</span></span><br><span class="line">  HAL_Init();</span><br></pre></td></tr></table></figure>

<p>，我的理解就是，可能就是简单的做一个初始化吧。在main.c调用完 HAL_Init() 函数后，立刻又调用了 SystemClock_Config()函数来配置时钟，这个系统滴答定时器又会被配置一次。</p>
<h2 id="2-SystemClock-Config-中的配置"><a href="#2-SystemClock-Config-中的配置" class="headerlink" title="2. SystemClock_Config()中的配置"></a><font size=3>2. SystemClock_Config()中的配置</font></h2><h3 id="2-1-SystemClock-Config"><a href="#2-1-SystemClock-Config" class="headerlink" title="2.1 SystemClock_Config()"></a><font size=3>2.1 SystemClock_Config()</font></h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">SystemClock_Config</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">  RCC_OscInitTypeDef RCC_OscInitStruct = &#123;<span class="number">0</span>&#125;;</span><br><span class="line">  RCC_ClkInitTypeDef RCC_ClkInitStruct = &#123;<span class="number">0</span>&#125;;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/** Initializes the RCC Oscillators according to the specified parameters</span></span><br><span class="line"><span class="comment">  * in the RCC_OscInitTypeDef structure.</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line">  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;</span><br><span class="line">  RCC_OscInitStruct.HSEState = RCC_HSE_ON;</span><br><span class="line">  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;</span><br><span class="line">  RCC_OscInitStruct.HSIState = RCC_HSI_ON;</span><br><span class="line">  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;</span><br><span class="line">  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;</span><br><span class="line">  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;</span><br><span class="line">  <span class="keyword">if</span> (HAL_RCC_OscConfig(&amp;RCC_OscInitStruct) != HAL_OK)</span><br><span class="line">  &#123;</span><br><span class="line">    Error_Handler();</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/** Initializes the CPU, AHB and APB buses clocks</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line">  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK</span><br><span class="line">                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;</span><br><span class="line">  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;</span><br><span class="line">  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;</span><br><span class="line">  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;</span><br><span class="line">  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (HAL_RCC_ClockConfig(&amp;RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)</span><br><span class="line">  &#123;</span><br><span class="line">    Error_Handler();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>经过这个函数的配置，我们得到的时钟如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">SYSCLK(系统时钟)             = <span class="number">72</span>MHz</span><br><span class="line">PLL 主时钟                   = <span class="number">72</span>MHz</span><br><span class="line">AHB 总线时钟（HCLK=SYSCLK/<span class="number">1</span>） = <span class="number">72</span>MHz</span><br><span class="line">APB1 总线时钟（PCLK1=HCLK/<span class="number">2</span>） = <span class="number">36</span>MHz</span><br><span class="line">APB2 总线时钟（PCLK2=HCLK/<span class="number">1</span>） = <span class="number">72</span>MHz</span><br></pre></td></tr></table></figure>

<p>根据前边分析的系统滴答定时器的始终来源，这里用于系统滴答定时器的时钟为 AHB时钟，也就是72M。</p>
<h3 id="2-2-HAL-RCC-ClockConfig"><a href="#2-2-HAL-RCC-ClockConfig" class="headerlink" title="2.2 HAL_RCC_ClockConfig()"></a><font size=3>2.2 HAL_RCC_ClockConfig()</font></h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">HAL_StatusTypeDef <span class="title function_">HAL_RCC_ClockConfig</span><span class="params">(RCC_ClkInitTypeDef  *RCC_ClkInitStruct, <span class="type">uint32_t</span> FLatency)</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="comment">// 中间的部分省略......</span></span><br><span class="line">  <span class="comment">/* Update the SystemCoreClock global variable */</span></span><br><span class="line">  SystemCoreClock = HAL_RCC_GetSysClockFreq() &gt;&gt; AHBPrescTable[(RCC-&gt;CFGR &amp; RCC_CFGR_HPRE) &gt;&gt; RCC_CFGR_HPRE_Pos];</span><br><span class="line"></span><br><span class="line">  <span class="comment">/* Configure the source of time base considering new system clocks settings*/</span></span><br><span class="line">  HAL_InitTick(uwTickPrio);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我没有具体去追踪这个 SystemCoreClock 试是怎么被获取出来的，但是根据猜测，这里应该是系统时钟，我前边试配置成了72M（这是个全局变量，也可以在配置完成后，串口打印一下）:</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230503105812871.png" alt="image-20230503105812871" style="zoom: 80%;" />

<p>这样我们从这里得到两个参数：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">SystemCoreClock = <span class="number">72000000</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> __NVIC_PRIO_BITS           4U   <span class="comment">/*!&lt; STM32 uses 4 Bits for the Priority Levels    */</span></span></span><br><span class="line">uwTickPrio = (<span class="number">1UL</span> &lt;&lt; __NVIC_PRIO_BITS); <span class="comment">/* Invalid PRIO */</span></span><br><span class="line">           = <span class="number">1</span> &lt;&lt; <span class="number">4</span></span><br></pre></td></tr></table></figure>

<h3 id="2-3-HAL-InitTick"><a href="#2-3-HAL-InitTick" class="headerlink" title="2.3 HAL_InitTick()"></a><font size=3>2.3 HAL_InitTick()</font></h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">__weak HAL_StatusTypeDef <span class="title function_">HAL_InitTick</span><span class="params">(<span class="type">uint32_t</span> TickPriority)</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="comment">// 中间部分省略</span></span><br><span class="line">  <span class="keyword">if</span> (HAL_SYSTICK_Config(SystemCoreClock / (<span class="number">1000U</span> / uwTickFreq)) &gt; <span class="number">0U</span>)</span><br><span class="line">  &#123;</span><br><span class="line">    <span class="keyword">return</span> HAL_ERROR;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 中间部分省略</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这个函数前边了解过了，这里传入的参数就变成了：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">HAL_SYSTICK_Config(<span class="number">72000000</span> / (<span class="number">1000U</span> / <span class="number">1</span>);</span><br><span class="line"><span class="comment">// 即</span></span><br><span class="line">HAL_SYSTICK_Config(<span class="number">72000</span>);</span><br></pre></td></tr></table></figure>

<h3 id="2-4-HAL-SYSTICK-Config"><a href="#2-4-HAL-SYSTICK-Config" class="headerlink" title="2.4 HAL_SYSTICK_Config()"></a><font size=3>2.4 HAL_SYSTICK_Config()</font></h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">uint32_t</span> <span class="title function_">HAL_SYSTICK_Config</span><span class="params">(<span class="type">uint32_t</span> TicksNumb)</span></span><br><span class="line">&#123;</span><br><span class="line">   <span class="keyword">return</span> SysTick_Config(TicksNumb);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里跟前边一样，没啥好说的，只是这里的参数会变成如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SysTick_Config(<span class="number">72000</span>)</span><br></pre></td></tr></table></figure>

<h3 id="2-5-SysTick-Config"><a href="#2-5-SysTick-Config" class="headerlink" title="2.5 SysTick_Config()"></a><font size=3>2.5 SysTick_Config()</font></h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">__STATIC_INLINE <span class="type">uint32_t</span> <span class="title function_">SysTick_Config</span><span class="params">(<span class="type">uint32_t</span> ticks)</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="keyword">if</span> ((ticks - <span class="number">1UL</span>) &gt; SysTick_LOAD_RELOAD_Msk)</span><br><span class="line">  &#123;</span><br><span class="line">    <span class="keyword">return</span> (<span class="number">1UL</span>);                                                   <span class="comment">/* Reload value impossible */</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  SysTick-&gt;LOAD  = (<span class="type">uint32_t</span>)(ticks - <span class="number">1UL</span>);                         <span class="comment">/* set reload register */</span></span><br><span class="line">  NVIC_SetPriority (SysTick_IRQn, (<span class="number">1UL</span> &lt;&lt; __NVIC_PRIO_BITS) - <span class="number">1UL</span>); <span class="comment">/* set Priority for Systick Interrupt */</span></span><br><span class="line">  SysTick-&gt;VAL   = <span class="number">0UL</span>;                                             <span class="comment">/* Load the SysTick Counter Value */</span></span><br><span class="line">  SysTick-&gt;CTRL  = SysTick_CTRL_CLKSOURCE_Msk |</span><br><span class="line">                   SysTick_CTRL_TICKINT_Msk   |</span><br><span class="line">                   SysTick_CTRL_ENABLE_Msk;                         <span class="comment">/* Enable SysTick IRQ and SysTick Timer */</span></span><br><span class="line">  <span class="keyword">return</span> (<span class="number">0UL</span>);                                                     <span class="comment">/* Function successful */</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>到这里，开始配置寄存器，我们前边知道AHB的时钟为72MHz，这里重载值寄存器配置为72000-1&#x3D;71999，我们再看一下控制寄存器中是否对时钟分频了：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">define</span> SysTick_CTRL_CLKSOURCE_Pos          2U                                            <span class="comment">/*!&lt; SysTick CTRL: CLKSOURCE Position */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> SysTick_CTRL_CLKSOURCE_Msk         (1UL &lt;&lt; SysTick_CTRL_CLKSOURCE_Pos)            <span class="comment">/*!&lt; SysTick CTRL: CLKSOURCE Mask */</span></span></span><br></pre></td></tr></table></figure>

<p>从这两个宏可知，SysTick_CTRL_CLKSOURCE_Msk 的值就是 1左移 2位，对应到 CTRL 寄存器，就是第2位了，这里将第2位置1，就表示不进行分频。</p>
<h3 id="2-6-中断产生时间"><a href="#2-6-中断产生时间" class="headerlink" title="2.6 中断产生时间"></a><font size=3>2.6 中断产生时间</font></h3><p>上边经过分析，我们知道了系统滴答定时器的时钟为72MHz，不分频，重载值为72999，从0~72999一共是72000个数，我们来计算一下产生一次中断的时间:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">滴答定时器时钟 = <span class="number">72000000</span></span><br><span class="line">每计一个数时间 = <span class="number">1</span> / <span class="number">72000000</span></span><br><span class="line">共计<span class="number">72000</span>个数的时间 = <span class="number">72000</span> * <span class="number">1</span> / <span class="number">72000000</span> = <span class="number">1</span> / <span class="number">1000</span> = <span class="number">0.001</span>s = <span class="number">1</span>ms</span><br></pre></td></tr></table></figure>

<p>所以默认情况下，系统滴答定时器每过1ms就会产生一次中断。</p>
<h2 id="3-中断处理函数"><a href="#3-中断处理函数" class="headerlink" title="3. 中断处理函数"></a><font size=3>3. 中断处理函数</font></h2><p>接下来我们看一下中断处理函数：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SysTick_Handler()---&gt;HAL_IncTick()---&gt;HAL_IncTick()</span><br></pre></td></tr></table></figure>

<p>我们发现最终的回调函数为 HAL_IncTick ：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">__weak <span class="type">void</span> <span class="title function_">HAL_IncTick</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">  uwTick += uwTickFreq;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们来看一下里边的这句话：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">enum</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">  HAL_TICK_FREQ_10HZ         = <span class="number">100U</span>,</span><br><span class="line">  HAL_TICK_FREQ_100HZ        = <span class="number">10U</span>,</span><br><span class="line">  HAL_TICK_FREQ_1KHZ         = <span class="number">1U</span>,</span><br><span class="line">  HAL_TICK_FREQ_DEFAULT      = HAL_TICK_FREQ_1KHZ</span><br><span class="line">&#125; HAL_TickFreqTypeDef;</span><br><span class="line">HAL_TickFreqTypeDef uwTickFreq = HAL_TICK_FREQ_DEFAULT;  <span class="comment">/* 1KHz */</span></span><br><span class="line"></span><br><span class="line">__IO <span class="type">uint32_t</span> uwTick;</span><br></pre></td></tr></table></figure>

<p>于是就有：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">uwTick += uwTickFreq;</span><br><span class="line"><span class="comment">// 等价于</span></span><br><span class="line">uwTick = uwTick + <span class="number">1</span>；</span><br></pre></td></tr></table></figure>

<p>所以默认情况下的系统滴答定时器会不停地在中断中计数，注意uwTick是一个全局变量，其他地方也都可以用。</p>
<h2 id="4-HAL-Delay"><a href="#4-HAL-Delay" class="headerlink" title="4. HAL_Delay()"></a><font size=3>4. HAL_Delay()</font></h2><p>接下来我们看一下这个库中的延时函数的实现：</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV16-STM32%E5%BC%80%E5%8F%91/LV16-17-SysTick%E5%AE%9A%E6%97%B6%E5%99%A8/img/image-20230503112220723.png" alt="image-20230503112220723" style="zoom: 80%;" />

<p>我们来分析一下：</p>
<p>（1）tickstart的值等于调用此延时函数时 全局变量 uwTick 的值；</p>
<p>（2）wait的值为我们要延时的ms数；</p>
<p>（3）判断一下wait时间是不是比最大延时时间短，若是比最大的延时时间还要短的话，就会将 wait 的值加上最小延时时间，这里是1，就表示我们延时最短是1ms。</p>
<p>（4）进入循环等待，当uwTick 的值减去进入函数时的值等于wait的时候，while循环条件为假，退出循环，开始执行HAL_Delay后边的代码，达到延时的效果。</p>
<blockquote>
<p>有几个问题：</p>
<p>（1）这里我们延时的话，Delay输入了个小于等于-1的值怎么办？按-1来算，进来后，加一为0，下边循环直接就不满足了，直接退出；比-1小的话也是一样的结果。</p>
<p>（2）延时时间打与大于0xFFFFFFFF？我们传入参数的时候形参是个uint32_t类型，这就是一个32位数据，比它还大的话，会溢出，高位就没了，所以最大延时时间还是 0xFFFFFFFF。</p>
</blockquote>

    </div>

    
    
    

    <footer class="post-footer">




    <div>
        
            <div style="text-align:center;color: #ccc;font-size:14px;">
            ----------本文结束
            <i class="fas fa-fan fa-spin" style="color: #FF1493; font-size: 1rem"></i>
            感谢您的阅读----------
            </div>
        
    </div>





  
  <div class="my_post_copyright"> 
    <p><span>文章标题:</span><a href="/post/787934fe.html">LV16-17-SysTick定时器</a></p>
    <p><span>文章作者:</span><a href="/" title="欢迎访问 《苏木》 的学习笔记">苏木</a></p>
    <p><span>发布时间:</span>2023年06月04日 - 22:07</p>
    <p><span>最后更新:</span>2025年06月14日 - 00:25</p>
    <p><span>原始链接:</span><a href="/post/787934fe.html" title="LV16-17-SysTick定时器">https://sumumm.github.io/post/787934fe.html</a></p>
    <p><span>许可协议:</span><i class="fab fa-creative-commons"></i> <a rel="license" href= "https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
  </div>
  


          <div class="post-tags">
              <a href="/tags/LV16-STM32%E5%BC%80%E5%8F%91/" rel="tag"><i class="fa fa-tag"></i> LV16-STM32开发</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/post/c7f567c8.html" rel="prev" title="LV16-18-DMA-01-DMA基础知识">
                  <i class="fa fa-angle-left"></i> LV16-18-DMA-01-DMA基础知识
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/post/e937a4ef.html" rel="next" title="LV16-16-STM32时钟系统">
                  LV16-16-STM32时钟系统 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2017 – 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">苏木</span>
  </div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">3.7m</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">225:26</span>
  </span>
</div>




    <span id="sitetime"></span>
    <script defer language=javascript>
        function siteTime()
        {
            window.setTimeout("siteTime()", 1000);
            var seconds = 1000;
            var minutes = seconds * 60;
            var hours = minutes * 60;
            var days = hours * 24;
            var years = days * 365;
            var today = new Date();
            var todayYear = today.getFullYear();
            var todayMonth = today.getMonth()+1;
            var todayDate = today.getDate();
            var todayHour = today.getHours();
            var todayMinute = today.getMinutes();
            var todaySecond = today.getSeconds();
            /*==================================================
            Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
            year        - 作为date对象的年份，为4位年份值
            month       - 0-11之间的整数，做为date对象的月份
            day         - 1-31之间的整数，做为date对象的天数
            hours       - 0(午夜24点)-23之间的整数，做为date对象的小时数
            minutes     - 0-59之间的整数，做为date对象的分钟数
            seconds     - 0-59之间的整数，做为date对象的秒数
            microseconds - 0-999之间的整数，做为date对象的毫秒数
            ==================================================*/
            var t1 = Date.UTC(2017, 
                              5, 
                              19, 
                              0, 
                              0, 
                              0); //北京时间
            var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
            var diff = t2-t1;
            var diffYears = Math.floor(diff/years);
            var diffDays = Math.floor((diff/days)-diffYears*365);
            var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
            var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
            var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
            document.getElementById("sitetime").innerHTML="已在这里 "+diffYears+" 年 "+diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒";
        }
        siteTime();
    </script>



    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.umd.js" integrity="sha256-ytMJGN3toR+a84u7g7NuHm91VIR06Q41kMWDr2pq7Zo=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.16.0/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>

  <script src="/js/third-party/pace.js"></script>


  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>


 
        <div id="click-show-text"
            data-mobile = false
            data-text = 富强,民主,文明,和谐,自由,平等,公正,法制,爱国,敬业,诚信,友善
            data-fontsize = 15px
            data-random= false>
        </div>
       

      
        <script async src=https://cdn.jsdelivr.net/npm/hexo-next-mouse-effect@latest/click/showText.js></script>
      

      
    




    <script async src="/js/fancybox_param.js"></script>





<!-- APlayer本体 -->



</body>
</html>
